import api from '@/api'
import { Menu } from '@/types/api'
import { isArray } from 'lodash-es'

export interface IAuthLoader {
  buttonList: string[]
  menuList: Menu.MenuItem[]
  menuPathList: string[]
}

/**
 * 筛选路由地址 ****
 * @param list 源数据
 * @returns
 */
const getMenuPath = (list: Menu.MenuItem[] = []): string[] => {
  return list.reduce((result: string[], item: Menu.MenuItem) => {
    // 权限按钮在最后一层
    return result.concat(isArray(item.children) && !item.buttons ? getMenuPath(item.children) : item.path + '')
  }, [])
}

// **** router loader
export default async function AuthLoader() {
  const data = await api.getPermissionList() // 获取权限列表
  const menuPathList = getMenuPath(data.menuList)
  return {
    buttonList: data.buttonList, // 按钮权限
    menuList: data.menuList, // 菜单渲染
    menuPathList // 获取的所有路由路径，做页面路由权限判断
  }
}
